package com.mvc.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.mvc.model.Person;

@Controller
@RequestMapping("/ajax")
public class AjaxController {
	private List<Person> persons=new ArrayList<Person>();
	public AjaxController(){
		persons.add(new Person(111,"我是中国第1人",22,"abc@123.com",new Date()));
		persons.add(new Person(111,"我是中国第2人",32,"abc@123.com",new Date()));
		persons.add(new Person(111,"我是中国第3人",42,"abc@123.com",new Date()));
		persons.add(new Person(111,"我是中国第4人",52,"abc@123.com",new Date()));
		persons.add(new Person(111,"我是中国第5人",62,"abc@123.com",new Date()));
		persons.add(new Person(111,"我是中国第6人",72,"abc@123.com",new Date()));
	}
	
	@RequestMapping("/ajax.do")
	public String toAjax() {
		return "ajax";
	}
	
	@RequestMapping("/list.ajax")
	@ResponseBody
	public Object list(){
		return persons;
	}
	
	/**
	 * 返回结果是一个对象
	 * @param index
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/person.json",method=RequestMethod.GET)
	public String show(@RequestParam int index,Model model){
		model.addAttribute(persons.get(index));
		return "person";
	}
	
	/**
	 * 返回结果是json字符串
	 * @param index
	 * @return
	 */
	@RequestMapping(value="/person.json",method=RequestMethod.GET,params="json")
	@ResponseBody
	public Object show(@RequestParam int index){
		System.out.println("Pserson==========>"+persons.get(index));
		return persons.get(index);
	}
	
	@RequestMapping(value = "/printWriter.json", method = RequestMethod.GET )
	@ResponseBody
	public void ajaxWriter(PrintWriter printWriter, HttpServletResponse response) throws IOException {

		System.out.println(persons.size());
		String jsonString = JSON.toJSONString(persons);

		/*
		 * System.out.println("jsonString:"+jsonString);
		 * response.setCharacterEncoding("utf-8");
		 * response.getWriter().write(jsonString);
		 * System.out.println("jsonString="+jsonString);
		 */

		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(jsonString.toString());
		
		/*
		 * printWriter.write(jsonString.toCharArray()); printWriter.flush();
		 * printWriter.close();
		 */
	}

}
